import React, { useState } from 'react'
import { Form, Input, Button, Modal, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import '../assets/styles/pages/login.scss'
import { handleLogin } from '../store/user/actionCreators'
import { connect } from 'react-redux'
import { showLoad, hideLoad } from '../utils/globalLoading.js'
import { getServiceInfo } from '../store/page/actionCreators'

const Login = (props) => {
  const [userName, setUserName] = useState('')
  const [password, setPassword] = useState('')
  const userNameChange = (e) => {
    setUserName(e.target.value)
  }
  const passwordChange = (e) => {
    setPassword(e.target.value)
  }

  const onFinish = async (values) => {
    try {
      showLoad()
      // await login(userName, password)
      // 存储token
      await props.handleLogin(userName, password)
      message.success('登录成功')
      await getCMS()
      props.history.push('/')
    } catch (e) {
      console.log(e)
      Modal.error({
        title: '错误',
        content: e.message,
      })
    } finally {
      hideLoad()
    }
  }
  const onFinishFailed = (err) => {
    console.log(err)
  }

  const getCMS = async () => {
    try {
      showLoad()
      await props.getServiceInfo()
    } catch (e) {
      // history.replace('/login')
    } finally {
      hideLoad()
    }
  }

  return (
    <div className="login">
      <div className="login-wrapper">
        <Form
          labelCol={{
            span: 6,
          }}
          size="middle"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              placeholder="请输入用户名"
              prefix={<UserOutlined />}
              allowClear
              value={userName}
              onChange={userNameChange}
            ></Input>
          </Form.Item>
          <Form.Item
            label="密　码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              placeholder="请输入密码"
              prefix={<LockOutlined />}
              allowClear
              value={password}
              onChange={passwordChange}
            ></Input.Password>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

const stateToProps = (state, props) => {
  return {
    ...props,
    ...state,
  }
}

const actionToProps = {
  handleLogin,
  getServiceInfo,
}

export default connect(stateToProps, actionToProps)(Login)
